package com.xxl.vueadmin.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapBuilder;
import com.google.code.kaptcha.Producer;
import com.xxl.vueadmin.common.Result;
import com.xxl.vueadmin.utils.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @version 1.0
 * @Author: 许啸林
 * @Date: 2021/7/29 14:27
 */
@RestController
public class AuthController extends  BaseController{
    @Autowired
    Producer producer;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 生成图片验证码
     * @return
     */
    @GetMapping("/getCaptcha")
    public Result getCaptcha() throws IOException {
        // 生成图片对象并转换成字节输出流
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", byteArrayOutputStream);

        // 获取图片字节数组并转换成base64格式
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String imagePrefix =  "data:image/jepg;base64,";
        String base64Image = imagePrefix + base64Encoder.encode(byteArrayOutputStream.toByteArray());
        String key = UUID.randomUUID().toString();
        redisUtils.hset(Const.CAPTCHA_KEY, key, code,1200);

        return Result.success(MapBuilder.create().put("capToken", key)
                                                 .put("captcha", base64Image)
                                                 .build());
    }
    @PreAuthorize("hasRole('admin')")
    @GetMapping("/test")
    public Result test() {
        return Result.success(null);
    }

    @GetMapping("/pass")
    public Result getPassword(String password) {
        String passowrdEcode = bCryptPasswordEncoder.encode(password);
        boolean matches = bCryptPasswordEncoder.matches(password, passowrdEcode);
        System.out.println(matches);
        return Result.success(passowrdEcode);
    }


}
